package com.company.book_store.web.servlet;

import com.alibaba.fastjson.JSON;
import com.company.book_store.pojo.Admin;
import com.company.book_store.pojo.User;
import com.company.book_store.service.Adminservicce;
import com.company.book_store.service.Iadminservice;
import com.company.book_store.service.Iuserservice;
import com.company.book_store.service.UserserviceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("account");
        String password = req.getParameter("password");
        String identity = req.getParameter("identity");
        Iuserservice server = new UserserviceImpl();
        Iadminservice iadminservice = new Adminservicce();
        String josnStr;
        Map<String,Integer>map  = new HashMap<>();
        if(identity.equals("user")){
            User user = new User(username,password);
           User user1 = server.selectByidandpsw(user);
            if(user1!= null){
                HttpSession session =req.getSession();
                session.setAttribute("username","user");
                System.out.println("servlet中seessionID"+session.getId());
                map.put("massage",1);
            }
            else{
                map.put("massage",0);
            }
        }
      else{
            Admin admin = new Admin(username,password);
            int i = iadminservice.selectbyadnandpsw(admin);
            System.out.println(i);
            if(i == 1){
                map.put("massage",1);
            }
            else{
                map.put("massage",0);
            }
        }
        josnStr = JSON.toJSONString(map);
        PrintWriter out = resp.getWriter();

        out.write(josnStr);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(11);
    }
}
